package com.zk.lettcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 字符串转换整数 (atoi)
 * @Author: zhang kai
 * @Date: 2021/11/08
 * @Description: https://leetcode-cn.com/problems/string-to-integer-atoi/
 */
public class Practice4 {

    public static int myAtoi(String s) {
        int len = s.length();
        char[] cs = s.toCharArray();
        int index = 0;
        //去除前置空格，不能使用trim
        while (cs[index] == ' ') {
            index++;
        }
        //去除空格后是否无值
        if (index == len){
            return 0;
        }
        //标志位正数还是负数
        int sign = 1;
        if (cs [index] == '-') {
            sign = -1;
            index++;
        } else if (cs[index] == '+') {
            index++;
        }
        int res = 0;
        while (index < len) {
            char currentChar = cs[index];
            //判断当前字符是否在0-9之间
            if (currentChar > '9' || currentChar < '0') {
                break;
            }
            //先判断加上后一位后是否会超出int最大值
            //根据如果目前值大于最大值除10，那么说明此数字再加上一位肯定大于最大值
            //也可能出现正好相等的情况
            if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE /10 && (currentChar - '0') > Integer.MAX_VALUE % 10)) {
                return Integer.MAX_VALUE;
            }
            if (res < Integer.MIN_VALUE /10 || (res == Integer.MIN_VALUE /10 && (currentChar - '0') > -(Integer.MIN_VALUE%10))) {
                return Integer.MIN_VALUE;
            }
            //正数相加，负数相减
            res = res * 10 + sign *(currentChar - '0');
        }
        return res;
    }
}
